package com.ruoyi.livesass.api.sync;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cyl.manager.lbs.domain.LbsZbjl;
import com.cyl.manager.lbs.mapper.LbsZbjlMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ruoyi.livesass.LiveVideoService;
import com.ruoyi.livesass.api.domain.LbsZbll;
import com.ruoyi.livesass.api.mapper.LbsZbllMapper;
import com.ruoyi.livesass.api.service.LbsZbllService;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import com.volcengine.model.livesaas.response.GetLiveTrafficPostPayDataResponse;
import com.volcengine.model.livesaas.response.GetLiveTrafficPostPayDataResponse.LiveTrafficData;
import com.volcengine.model.livesaas.response.ListActivityAPIResponse;
import com.volcengine.model.livesaas.response.ListActivityAPIResponse.ListActivityAPIForm;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;

/**
 * @ClassName: LiveTrafficDataSynService
 * @Description: TODO(直播流量数据同步 -- 流量数据统计)
 * @author 晏大兵
 * @date 2025年2月10日 上午11:13:23
 */
@Component("zbllSyn")
@Order(3)
public class LiveTrafficDataSynService implements ApplicationRunner {



	private static final Logger LOG = LoggerFactory.getLogger(LiveTrafficDataSynService.class);

	@Autowired
	LiveVideoService liveVideoService;

	@Autowired
	LbsZbllService lbsZbllService;

	@Autowired
	private LbsZbllMapper lbsZbllMapper;

	@Autowired
	private LbsZbjlMapper lbsZbjlMapper;
	
	@Value("${custom.synTasks.liveTrafficTask}")
	private String liveTrafficTask;
	
	//@Value("${custom.hsSubUserName}")
	//private String hsSubUserName;
	
	@Value("${custom.synTaskEnable}")
	private boolean synTaskEnable;
	
	private Map<String, Long> subNameDeptid = Maps.newHashMap();
	
    @Autowired
    private ISysConfigService configService;
    
    
	@Value("${custom.llxs:1.3}")
	private double llxs;
	
	
	@Value("${custom.lldj:0.09}")
	private double lldj;
	
	
	//@Scheduled(cron  = "${custom.synTasks.liveTrafficTask}")
    public void performTask() throws Exception {
		if(!synTaskEnable) {
			return ;
		}
		
        System.out.println("直播流量数据同步开始 ：" + System.currentTimeMillis());
        
        try {
        	subNameDeptid = Maps.newHashMap();
			this.syncLoadSysConfig();
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("定时任务异常 | 重新执行");
			Thread.sleep(2000);
			performTask();
		}
        
        System.out.println("直播流量数据同步结束 ：" + System.currentTimeMillis());
    }
	

	@Override
	public void run(ApplicationArguments args) throws Exception {
		try {
			System.out.println("llxs: " + llxs);
			System.out.println("lldj" + lldj);
			if(!synTaskEnable) {
				return ;
			}
			
			//this.syncLoadSysConfig();
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	public void syncLoadSysConfig() throws Exception {
		SysConfig sysConfig = configService.selectConfigByKey2("sys_config");
		if(null != sysConfig && !StrUtil.isBlankIfStr(sysConfig.getRemark())) {
			JSONObject sysConfigJsonObject = JSONObject.parseObject(sysConfig.getRemark());
			if(sysConfigJsonObject.containsKey("activityConfig")) {
				JSONArray activityConfigList = sysConfigJsonObject.getJSONArray("activityConfig");
				for(int i = 0 ; i < activityConfigList.size() ; i++ ) {
					JSONObject item = activityConfigList.getJSONObject(i);
					String subName = item.getString("subusername");
					if(!subNameDeptid.containsKey(subName)) {
						subNameDeptid.put(item.getString("subusername"), item.getLongValue("zbjid"));
						this.syncLiveVideoFlows(item.getString("subusername"), item.getLongValue("zbjid"));
					}
				}
			}
		}
	}
	

	/**
	 * @Title: syncLiveVideoFlows
	 * @Description: TODO(同步直播流量数据)
	 * @param 设定文件
	 * @return void 返回类型
	 * @throws Exception
	 * @throws
	 */
	public void syncLiveVideoFlows(String userName, long deptZbjId) throws Exception {

		
		
		// 首先查询出需要统计的直播间
		int pageNo = 1;
		int pageItemCount = 10000;
		int status = 4; //已结束的直播间
		String sortBy = "LiveTime";
		String sortOrder = "Desc";

		// 最近一个月得
		DateTime now = DateTime.now();
		DateTime offset = now.offset(DateField.DAY_OF_YEAR, -10);
		long liveTime = (offset.toJdkDate().getTime() / 1000);

		ListActivityAPIResponse listActivityAPIResponse = liveVideoService.listActivity(pageNo, pageItemCount, userName,
				status, sortBy, sortOrder, liveTime);
		List<ListActivityAPIForm> listActivityAPIForm = listActivityAPIResponse.getResult().getActivities();

		Map<Long, ListActivityAPIForm> activityInfoMap = Maps.newHashMap();

		List<Long> activityIds = Lists.newArrayList();

		for (ListActivityAPIForm item : listActivityAPIForm) {
			activityIds.add(item.getId());
			activityInfoMap.put(item.getId(), item);
		}

		// 开始获取直播间流量消耗
		// 时间偏移2天并且时长等于1个月
		// 系统当前时间
		LocalDateTime localDateTime = LocalDateTimeUtil.now();
		LocalDateTime endTime = LocalDateTimeUtil.offset(localDateTime, -1, ChronoUnit.DAYS);
		LocalDateTime startTime = LocalDateTimeUtil.offset(endTime, -10, ChronoUnit.DAYS);
		startTime = LocalDateTimeUtil.offset(startTime, +1, ChronoUnit.DAYS);

		String endDay = endTime.format(DatePattern.PURE_DATE_FORMATTER);
		String startDay = startTime.format(DatePattern.PURE_DATE_FORMATTER);

		LOG.error("获取直播流量数据 [StartDay:" + startDay + "],[EndDay:" + endDay+"] ,[activityIds:" + activityIds+"]");
		//可能QPS不够导致TimeOut
		Thread.sleep(500);
		
		if(null == activityIds || activityIds.size() == 0) {
			return ;
		}
		
		
		GetLiveTrafficPostPayDataResponse payDataResponse = liveVideoService.getLiveTrafficPostPayData(activityIds, null, startDay, endDay);
		List<LiveTrafficData> prePayList = payDataResponse.getResult().getActualPrePayResult();
		Map<String, LbsZbll> lbsZbllMap = processLiveTrafficData(activityInfoMap, prePayList);
		saveLbsZbll(lbsZbllMap, userName, deptZbjId);
		

		
	}

	/**
	 * 
	 * @Title: processLiveTrafficData
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param  activityInfoMap
	 * @param @param  activityGroupInfoMap
	 * @param @param  prePayList
	 * @param @return 设定文件
	 * @return Map<String,LbsZbll> 返回类型
	 * @throws
	 */
	private Map<String, LbsZbll> processLiveTrafficData(Map<Long, ListActivityAPIForm> activityInfoMap,
			List<LiveTrafficData> prePayList) {

		Map<String, LbsZbll> lbsZbllMap = Maps.newHashMap();

		for (LiveTrafficData item : prePayList) {

			ListActivityAPIForm activityInfo = activityInfoMap.get(item.getActivityId());

			long activityLiveTime = activityInfo.getLiveTime();
			LocalDateTime gsrqDateTime = LocalDateTimeUtil.ofUTC(activityLiveTime * 1000);
			String gsrq = gsrqDateTime.format(DatePattern.NORM_DATE_FORMATTER);

			LbsZbll lbsZbllItem = null;
			System.out.println("gsrq | " + gsrq);
			if (lbsZbllMap.containsKey(gsrq)) {
				lbsZbllItem = lbsZbllMap.get(gsrq);
				lbsZbllItem.setUpdateTime(LocalDateTimeUtil.now());
			} else {
				lbsZbllItem = new LbsZbll();
				lbsZbllItem.setGsrq(gsrq);
				lbsZbllItem.setCreateTime(LocalDateTimeUtil.now());
				lbsZbllMap.put(gsrq, lbsZbllItem);
			}

			// 观看人数合并
			long reGkrs = 0;
			if (null != lbsZbllItem.getGkrs()) {
				reGkrs = lbsZbllItem.getGkrs();
			}
			lbsZbllItem.setGkrs(reGkrs + item.getLiveUV());

			// 直播流量合并
			double reZbll = 0;
			if (null != lbsZbllItem.getZbll()) {
				reZbll = lbsZbllItem.getZbll().doubleValue();
			}
			
			//TODO 这里乘一个系数后在加上之前的流量
			double zbll = (item.getLiveTraffic() * llxs) + reZbll;
			lbsZbllItem.setZbll(BigDecimal.valueOf(zbll));

			// 合并直播间ID
			String zbjids = null;
			if (null != lbsZbllItem.getSszbjid() && !"".equals(lbsZbllItem.getSszbjid())) {
				zbjids = lbsZbllItem.getSszbjid() + "," + item.getActivityId();
			} else {
				zbjids = "" + item.getActivityId();
			}
			lbsZbllItem.setSszbjid(zbjids);

			System.out.println("LiveTrafficData | ActivityId[" + item.getActivityId() + "]," + "LiveTraffic["
					+ item.getLiveTraffic() + "], LiveUV[" + item.getLiveUV() + "],  LiveTime[" + activityLiveTime
					+ "]");
		}

		return lbsZbllMap;
	}

	/**
	 * 
	 * @Title: saveLbsZbll
	 * @Description: TODO(数据入库)
	 * @param @param lbsZbllMap 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	private void saveLbsZbll(Map<String, LbsZbll> lbsZbllMap, String userName, long deptZbjId) {

		for (String gsrqKey : lbsZbllMap.keySet()) {
			LbsZbll lbsZbll = lbsZbllMap.get(gsrqKey);

			QueryWrapper<LbsZbll> qw = new QueryWrapper();
			qw.eq("gsrq", lbsZbll.getGsrq());
			qw.eq("subname", userName);
			qw.eq("dept_zbj_id", deptZbjId);
			lbsZbllMapper.delete(qw);

			BigDecimal zbll = lbsZbll.getZbll();
			double zbllfy = (zbll.doubleValue() * lldj);

			lbsZbll.setZbllfy(new BigDecimal(zbllfy));

			lbsZbll.setSubname(userName);
			lbsZbll.setDeptZbjId(deptZbjId);
			lbsZbllMapper.insert(lbsZbll);

			// 更新直播间状态为无法在开播
			String[] zbjids = lbsZbll.getSszbjid().split(",");
			for (String zbjidItem : zbjids) {
				UpdateWrapper<LbsZbjl> uw = new UpdateWrapper<>();
				uw.eq("id", zbjidItem);
				uw.set("zbjzt", "107");
				lbsZbjlMapper.update(null, uw);
			}
		}

	}

}
